package org.pentaho.cubic.client.commands;

import org.pentaho.cubic.client.explorer.tab.CubicTabBarWidget;
import org.pentaho.cubic.client.explorer.tab.CubicTabLayoutPanel;

import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.NamedFrame;

public class PreviewReportCommand {
	private String xml;
	private String url;

	public PreviewReportCommand() {
		setupNativeHooks(this);
	}

	public PreviewReportCommand(String url, String xml) {
		this();
		this.xml = xml;
		this.url = url;
	}

	public static void setupNativeHooks() {
		new PreviewReportCommand();
	}

	private static native void setupNativeHooks(PreviewReportCommand cmd)
	/*-{
	    $wnd.mantle_waqr_preview = function(url, xml) {
	      cmd.@org.pentaho.cubic.client.commands.PreviewReportCommand::handleWAQRPreview(Ljava/lang/String;Ljava/lang/String;)(url, xml);
	    }
	}-*/;

	protected void performOperation() {
		CubicTabLayoutPanel contentPanel = CubicTabLayoutPanel.getInstance();
		NamedFrame content = new NamedFrame("" + System.currentTimeMillis());
		CubicTabBarWidget bar = new CubicTabBarWidget("Untitle Report", "Untitle Adhoc Report", contentPanel, content, true);
		contentPanel.add(content, bar);
		contentPanel.selectTab(content);
		
		final FormPanel form = new FormPanel(content);
		form.setMethod(FormPanel.METHOD_POST);
		form.setAction(url);
		form.add(new Hidden("reportXml", URL.encode(xml))); //$NON-NLS-1$
		form.submit();
	}

	protected void performOperation(final boolean feedback) {
		performOperation();
	}

	/**
	 * This method is called via JSNI
	 */
	private void handleWAQRPreview(String url, String xml) {
		PreviewReportCommand command = new PreviewReportCommand(url, xml);
		command.performOperation();
		//command.execute();
	}

}
